<template>
  <div class="left-sidebar">
    <div class="game-header">
      <h1 class="game-title">
        <span class="icon">🎨</span>
        涂色抢地盘
      </h1>
      <p class="game-subtitle">Territory Paint Battle</p>
    </div>

    <div class="timer-section">
      <div class="timer-box" :class="{ 'warning': currentTime <= 30, 'danger': currentTime <= 10 }">
        <div class="timer-label">剩余时间</div>
        <div class="timer-value">{{ formatTime(currentTime) }}</div>
      </div>
      <!-- 游戏状态显示 -->
      <div class="game-status">
        <div v-if="gameStatus === 'ready'" class="status-ready">
          <div class="status-icon">🎯</div>
          <div class="status-text">准备开始游戏</div>
          <div class="status-desc">点击上方"开始游戏"按钮即可开始</div>
        </div>
        <template v-else-if="gameStatus === 'playing'">
          <!-- 游戏进行中时，不再显示“等待开始”的提示，保持区域为空以节省空间 -->
        </template>
        <div v-else class="status-waiting">
          <div class="status-icon">⏳</div>
          <div class="status-text">等待开始</div>
          <div class="status-desc">请先进入游戏界面</div>
        </div>
      </div>
    </div>

    <!-- 全部玩家占领进度（动态排序） -->
    <div class="players-progress">
      <div class="pp-title">占领进度</div>
      <div class="pp-list">
        <div class="pp-item" v-for="p in sortedPlayers" :key="p.id">
          <div class="pp-row">
            <div class="pp-left">
              <span class="pp-color" :style="{ background: p.color || '#CBD5E1' }"></span>
              <span class="pp-name">{{ p.name }}</span>
            </div>
            <div class="pp-right">
              <span class="pp-pixels">{{ p.area || 0 }} px</span>
              <span class="pp-percent">{{ percentOf(p).toFixed(1) }}%</span>
            </div>
          </div>
          <div class="pp-bar">
            <div class="pp-fill" :style="{ width: percentOf(p) + '%', background: p.color || '#3B82F6' }"></div>
          </div>
        </div>
      </div>
      <div class="pp-total">总像素：{{ totalPixels }}</div>
    </div>

  </div>
</template>

<script setup>
import { onMounted, onUnmounted, computed } from 'vue'
// import { useUserStore } from '@/stores/user'

// 组件功能：游戏左侧边栏，显示游戏时间、玩家排行榜和游戏状态
// 定义组件名称
defineOptions({
  name: 'GameLeftSidebar'
})

// 定义 Props：输入参数
// 游戏剩余时间（秒）、游戏状态、玩家列表数据
const props = defineProps({
  gameTime: { type: Number, required: true },      // 游戏剩余时间（秒）
  gameStatus: { type: String, required: true },    // 游戏状态：waiting/playing/finished
  players: { type: Array, required: true },        // 玩家列表数据
  // 可选传入画布数据（仅用于统计像素总数等展示，不参与胜负计算）
  canvasData: { type: Object, default: () => ({ pixels: {} }) }
})

// 当前未对外发事件
// const emit = defineEmits(['time-up', 'game-finished'])

// 计算属性：活跃玩家数量（暂未在面板展示）
// 为避免未使用报错，按需启用
// const activePlayerCount = computed(() => props.players.filter(player => player.isActive !== false).length)

// 总面积
const totalArea = computed(() => props.players.reduce((s, p) => s + (p.area || 0), 0))

// 画布像素总数
const totalPixels = computed(() => {
  const pixels = props?.canvasData?.pixels || {}
  return Object.keys(pixels).length
})

// 当前用户玩家信息（如需显示“我的进度”可启用）
// const userStore = useUserStore()
// const currentUserId = computed(() => userStore.user?.id || userStore.user?.Id || userStore.user?.userId)
// const currentUserName = computed(() => userStore.user?.userName || userStore.user?.UserName)
// const currentUserPlayer = computed(() => {
//   const id = String(currentUserId.value || '')
//   const name = String(currentUserName.value || '')
//   const byId = props.players.find(p => String(p.id || '') === id)
//   if (byId) return byId
//   const byName = props.players.find(p => String(p.name || '') === name)
//   if (byName) return byName
//   const byYou = props.players.find(p => p.name === '你')
//   return byYou || null
// })

// const currentPixels = computed(() => Number(currentUserPlayer.value?.area) || 0)
// const myPercentage = computed(() => {
//   const total = totalArea.value || 0
//   return total > 0 ? (currentPixels.value / total) * 100 : 0
// })

// 排序后的玩家列表（按面积降序）
const sortedPlayers = computed(() => {
  return [...props.players]
    .map(p => ({ ...p, area: Number(p.area) || 0 }))
    .sort((a, b) => b.area - a.area)
})

const percentOf = (p) => {
  const total = totalArea.value || 0
  return total > 0 ? (Number(p.area || 0) / total) * 100 : 0
}

// 兼容占位：计时器由外部控制，这里提供空实现避免报错
const startCountdown = () => {}
const stopCountdown = () => {}

// 抑制未使用的开发期变量（排行榜/统计在后续版本启用）
// eslint-disable-next-line no-unused-vars
const __suppressUnused = [/* activePlayerCount, activePlayers, updateAreaStats, handleTimeUp */]

// 排行数据（暂未显示）
// const activePlayers = computed(() => { /* ... */ })

// 计时完全由父组件/全局 store 控制，这里只展示
const currentTime = computed(() => props.gameTime)

// 实时更新面积统计（当前不抛事件）
// const updateAreaStats = () => { /* ... */ }

// 计算获胜者
// NOTE: 备用算法已移除（未用）

// 备用：计算各玩家面积占比（当前未使用）
// const calculatePlayerAreas = () => { /* ... */ }

// 获取排行榜（降序）
// NOTE: 排行函数备用已移除（未用）

// const getPlayerColor = (playerIdOrName) => { /* ... */ }

// const getPlayerName = (playerId) => { /* ... */ }

// 时间到时的处理
// const handleTimeUp = () => { /* ... */ }

// 组件挂载时
onMounted(() => {
  // 如果游戏已经开始，立即开始倒计时
  if (props.gameStatus === 'playing') {
    startCountdown()
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopCountdown()
})

// mm:ss 格式化
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>

<style scoped>
.left-sidebar {
  width: 280px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.game-header {
  text-align: center;
}

.game-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 5px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.game-subtitle {
  font-size: 14px;
  opacity: 0.8;
  margin: 0;
}

.timer-section {
  text-align: center;
}

.timer-box {
  background-color: rgba(239, 68, 68, 0.9);
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.timer-box.warning {
  background-color: rgba(245, 158, 11, 0.9);
  animation: pulse 2s infinite;
}

.timer-box.danger {
  background-color: rgba(239, 68, 68, 0.9);
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

.timer-label {
  font-size: 14px;
  opacity: 0.9;
}

.timer-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 5px;
}

.game-status {
  color: #FEE2E2;
  font-weight: bold;
}

.status-ready, .status-playing, .status-waiting {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 10px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.1);
}

.status-icon {
  font-size: 24px;
}

.status-text {
  font-size: 18px;
  font-weight: bold;
}

.status-desc {
  font-size: 12px;
  opacity: 0.7;
  text-align: center;
}

/* 进度列表 */
.players-progress { background: rgba(255,255,255,0.95); border: 1px solid #e5e7eb; border-radius: 12px; padding: 12px; color: #111827; }
.pp-title { font-size: 14px; font-weight: 800; margin-bottom: 8px; }
.pp-list { display: flex; flex-direction: column; gap: 10px; }
.pp-item { display: block; }
.pp-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.pp-left { display: flex; align-items: center; gap: 8px; }
.pp-color { width: 12px; height: 12px; border-radius: 50%; border: 1px solid #e5e7eb; }
.pp-name { font-weight: 600; }
.pp-right { display: flex; align-items: center; gap: 10px; font-size: 12px; color: #6b7280; }
.pp-pixels { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; color: #374151; }
.pp-percent { font-weight: 700; color: #111827; }
.pp-bar { height: 8px; background: #f3f4f6; border-radius: 999px; overflow: hidden; }
.pp-fill { height: 100%; width: 0; transition: width .2s ease; }
.pp-total { margin-top: 8px; text-align: right; font-size: 12px; color: #6b7280; }

.player-rankings h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.player-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.1);
}

.player-item.current-player {
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.player-item.host-player {
  background-color: rgba(59, 130, 246, 0.3);
  border: 1px solid rgba(59, 130, 246, 0.5);
}

.player-item.ready-player {
  background-color: rgba(16, 185, 129, 0.2);
}

.player-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid white;
}

.player-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.player-avatar:hover {
  transform: scale(1.1);
  transition: transform 0.2s ease;
}

.player-info {
  display: flex;
  flex-direction: column;
  gap: 3px;
  flex: 1;
}

.player-name-row {
  display: flex;
  align-items: center;
  gap: 5px;
}

.player-level-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 11px;
}

.player-level {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
  padding: 2px 6px;
  border-radius: 8px;
  font-weight: bold;
  font-size: 10px;
}

.player-title {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
  color: white;
  padding: 2px 6px;
  border-radius: 8px;
  font-weight: bold;
  font-size: 10px;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.player-name {
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
}

.host-badge {
  background-color: #3B82F6;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

.ready-badge {
  background-color: #10B981;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

.player-game-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.5);
  flex-shrink: 0;
}

.player-score {
  font-weight: bold;
}

@media (max-width: 1200px) {
  .left-sidebar {
    width: 250px;
  }
}
</style>